package org.net5ijy.security.util.exception;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.util.RequestUtil;
import org.net5ijy.security.util.ResponseMessage;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 全局Controller异常处理器
 * 
 * @author 创建人：xuguofeng
 * @version 创建于：2018年9月17日 下午1:21:01
 */
@ControllerAdvice
public class ControllerExceptionHandler {

	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public ResponseMessage handleControllerException(
			HttpServletRequest request, HttpServletResponse response,
			Throwable ex) throws ServletException, IOException {

		// 获取标注在异常类上面的ResponseStatus注解
		ResponseStatus rs = ex.getClass().getAnnotation(ResponseStatus.class);
		// 如果异常类加了该注解，就去获取设置的状态码的值
		if (rs == null) {
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		} else {
			int status = rs.value().value();
			response.setStatus(status);
		}
		// 如果是AJAX请求，返回一个JSON回去
		if (RequestUtil.isAjax(request)) {
			ResponseMessage msg = ResponseMessage.error();
			msg.addAttribute("exception", ex.getMessage());
			return msg;
		}
		// 如果是正常请求，转发到/error50x
		request.setAttribute("exception", ex.getMessage());
		request.getRequestDispatcher("/error50x").forward(request, response);
		return null;
	}
}
